using System.Configuration;
using System.Xml;
using System.Collections.Generic;
using elmah2.core.interfaces;
using System;
using System.Linq;

namespace elmah2.core.config
{
  public sealed class FilterSection : IConfigurationSectionHandler
  {
    public List<Filter> Filters { get; set; }

    public object Create(object parent, object configContext, XmlNode section)
    {
      FilterSection config = new FilterSection();
      config.LoadValuesFromXml(section);
      return config;
    }

    private void LoadValuesFromXml(XmlNode section)
    {
      Filters = new List<Filter>();
      foreach (XmlNode childNode in section.ChildNodes)
      {
        if (childNode.Name.Equals("filter"))
        {
          Filters.Add(new Filter()
              {
                Config = InitConfigOptions(childNode),
                Type = childNode.Attributes["Type"].Value
              });
        }
      }
    }

    private Dictionary<string, string> InitConfigOptions(XmlNode childNode)
    {
      Dictionary<string, string> toReturn = new Dictionary<string, string>();
      foreach (XmlAttribute xla in childNode.Attributes)
        toReturn.Add(xla.Name, xla.Value);

      return toReturn;
    }
  }

  public sealed class Filter
  {
    public Dictionary<string, string> Config { get; set; }
    public string Type { get; set; }

    private static List<IErrorFilter> _filters;
    public static List<IErrorFilter> GetFilters()
    {
      if (_filters == null)
      {
        _filters = new List<IErrorFilter>();
        FilterSection config = (FilterSection)ConfigurationManager.GetSection("elmah2/filters");

        if (config == null)
          return null;

        foreach (var v in config.Filters)
        {
          Type type = System.Type.GetType(v.Type, true);
          IErrorFilter e1 = (IErrorFilter)Activator.CreateInstance(type, new object[] { });
          e1.Init(v.Config);
          _filters.Add(e1);
        }
      }
      return _filters;
    }
  }
}
